package love.yuanmengrobot.zframe.mvc;
/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:CHJY创幻
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/6/23 19:54
 */

import love.yuanmengrobot.zframe.mvc.annotation.Controller;
import love.yuanmengrobot.zframe.mvc.annotation.RequestMapping;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

public class Configuration {


    public Map<String, ControllerMapping> config() throws URISyntaxException, Exception {
        Map<String, ControllerMapping> controllerMapping = new HashMap<String, ControllerMapping>();
        try {

            SAXReader reader = new SAXReader();
            InputStream in = null;
            Document doc = null;
            List<Element> list;

            in = Class.forName("love.yuanmengrobot.zframe.mvc.Configuration")
                    .getResourceAsStream("/bean-factory.xml");
            doc = reader.read(in);
            list = doc.selectNodes("/beans/bean");
            for (Element e : list) {
                String id = e.attributeValue("id");
                if (id == null) continue;
                if ("controller".equals(id)) {
                    List<Element> childElements = e.elements();//得到ele的子元素集合
                    String controllerPackageName = null;
                    for (Element childEle : childElements) {
                        controllerPackageName = childEle.attributeValue("base-package");
//                        System.out.println("__________________扫描的controller："+controllerPackageName);


//            /*
//            读取config.properties文件，获取到包名称
//             */
//            ResourceBundle bundle = ResourceBundle.getBundle("config");
//            String controllerPackageName = bundle.getString("controller.package");
//            System.out.println(controllerPackageName);
//            String controllerPName[] = controllerPackageName.split(";");//包名有;分割
//            controllerPackageName = controllerPName[0];


//                            controllerPackageName = s;//遍历获取包名路径
                /*
                根据包名称构建要扫描的完整路径
                 */
                            String path = controllerPackageName.replace(".", "/");
                            if(Configuration.class.getResource("/" + path)==null)continue;
                            URI uri = Configuration.class.getResource("/" + path).toURI();
//                            System.out.println(uri);
                            File controllerDirectory = new File(uri);
                            String controllerFileNames[] = controllerDirectory.list();
                            for (String controllerFileName : controllerFileNames) {
                                //全限定类名=包名 + 类名
                                String controllerClassName = controllerPackageName + "." + StringUtils.substringBefore(controllerFileName, ".class");
                                //动态加载类
                                Class<?> controllerClass = Class.forName(controllerClassName);
                                //判断哪些类上使用了Controller注解
                                if (controllerClass.isAnnotationPresent(Controller.class)) {
                                    //获取类RequestMapping注解
                                    RequestMapping anHeader=controllerClass.getAnnotation(RequestMapping.class);
//                        System.out.println("headr注解:"+anHeader.value());

//                    继续找出哪些方法上使用了@RequestMapping注解
                                    Method[] handleMethods = MethodUtils.getMethodsWithAnnotation(controllerClass, RequestMapping.class);
                                    for (Method handleMethod : handleMethods) {
                                        RequestMapping annotation = handleMethod.getAnnotation(RequestMapping.class);
                                        ControllerMapping mapping = new ControllerMapping(controllerClass, handleMethod);
//                                        System.out.print("类：" + controllerClass.getSimpleName());
//                                        System.out.print("\t方法：" + handleMethod.getName());
//                                        System.out.println("\t类+方法注解的值："+anHeader.value() + annotation.value());
                                        controllerMapping.put(anHeader.value()+annotation.value(), mapping);

                        /*
                        拿到注解的值（url）以后，提前把url存入mapping中，将来前端控制器(DispatcherServlet收到请求后，把客户端的url去mappping中查找相应的url）
                        如果匹配到了url那么会自动去调用标记了url的那个方法
                         */
                                    }
                                }
                            }

                        }



                }
            }




        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return controllerMapping;
    }
}